package io.github.heollhai.common.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lmf
 * @Create: 2024/7/11 10:23
 * Description:
 */
public class MybatisPlusUtils {
    /**
     * 修改分页数据类型
     */
    public static <T, V> Page<V> changePageDataClass(Page<T> originPage, Class<V> newClass) {
        List<V> collect = originPage.getRecords().stream()
                .map(bo -> {
                    V v = null;
                    // 通过反射 创建新对象
                    try {
                        v = newClass.getDeclaredConstructor().newInstance();
                        BeanUtils.copyProperties(bo, v);
                    } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                             NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                    return v;
                }).toList();
        return new Page<V>(originPage.getCurrent(), originPage.getSize(), originPage.getTotal()).setRecords(collect);
    }

    /**
     * 修改数据类型
     */
    public static <T, V> List<V> changeDataClass(List<T> originList, Class<V> newClass) {
        return changeDataClass(originList, newClass, t -> {
        });
    }

    /**
     * 修改数据类型
     */
    public static <T, V> V changeDataClass(T originData, Class<V> newClass) {
        V v = null;
        if (originData == null) {
            return null;
        }
        try {
            v = newClass.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        BeanUtils.copyProperties(originData, v);
        return v;
    }

    @FunctionalInterface
    public interface BiConsumerWithVoid<T> {
        void accept(T t);
    }

    /**
     * 修改数据类型
     */
    public static <T, V> List<V> changeDataClass(List<T> originList, Class<V> newClass, BiConsumerWithVoid<T> mapper) {
        V v = null;
        try {
            ArrayList<V> vArrayList = new ArrayList<>();
            for (T t : originList) {
                v = newClass.getDeclaredConstructor().newInstance();
                mapper.accept(t);
                BeanUtils.copyProperties(t, v);
                vArrayList.add(v);
            }
            return vArrayList;

        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }


}
